import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { RabbitmqService } from '@app/rabbitmq';

@Injectable()
export class MessageService implements OnModuleInit {
  @Inject(RabbitmqService)
  private readonly rabbitmqService: RabbitmqService;

  async onModuleInit() {
    // 当模块初始化时，开始消费 'user_retrieved' 队列的消息
    await this.rabbitmqService.consume(
      'user_retrieved',
      this.handleUserRetrieved.bind(this),
    );
  }

  // 处理来自 'user_retrieved' 队列的消息
  async handleUserRetrieved(user: any) {
    console.log('处理用户信息:', user);

    // 模拟一些耗时操作
    await this.simulateHeavyProcessing();

    console.log(`用户 ${user.id} 的消息处理完成`);
  }

  async simulateHeavyProcessing() {
    return new Promise((resolve) => setTimeout(resolve, 2000)); // 每个消息处理耗时2秒
  }
}
